package com.lucien.system.service.impl;

import com.lucien.system.domain.SysGroupNotice;
import com.lucien.system.domain.SysGroupNoticeExample;
import com.lucien.system.domain.SysUser;
import com.lucien.system.mapper.SysGroupNoticeMapper;
import com.lucien.system.service.SysGroupNoticeService;
import com.lucien.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SysGroupNoticeImpl implements SysGroupNoticeService {

    @Autowired
    private SysGroupNoticeMapper noticeMapper;

    @Autowired
    private SysUserService userService;

    /**
     * 添加群公告
     * @param groupId
     * @param userId
     * @param title
     * @param content
     * @return
     */
    @Override
    public int insertNotice(Integer groupId, Integer userId, String title, String content) {
        SysGroupNotice groupNotice = new SysGroupNotice();
        SysUser sysUser = userService.selectByUserId(userId);
        groupNotice.setGroupId(groupId);
        groupNotice.setUserId(userId);
        groupNotice.setNickname(sysUser.getUsername());
        groupNotice.setAvatar(sysUser.getUserProfile());
        groupNotice.setTitle(title);
        groupNotice.setContent(content);
        groupNotice.setCreatedTime(new Date());

        if (noticeMapper.insert(groupNotice) != 1){
            return -1;
        }

        return 1;
    }

    /**
     * 获取群公告
     * @param groupId
     * @return
     */
    @Override
    public List<SysGroupNotice> listNotice(Integer groupId) {
        SysGroupNoticeExample example = new SysGroupNoticeExample();
        SysGroupNoticeExample.Criteria criteria = example.createCriteria();
        criteria.andGroupIdEqualTo(groupId);

        List<SysGroupNotice> notices = noticeMapper.selectByExample(example);

        return notices;
    }

    /**
     * 删除公告
     * @param id
     * @return
     */
    @Override
    public int delNotice(Long id) {
        if(noticeMapper.deleteByPrimaryKey(id) != 1){
            return -1;
        }
        return 1;
    }

    /**
     * 更新群公告
     * @param id
     * @param title
     * @param content
     * @return
     */
    @Override
    public int editNotice(Long id, String title, String content) {
        SysGroupNotice groupNotice = noticeMapper.selectByPrimaryKey(id);
        groupNotice.setTitle(title);
        groupNotice.setContent(content);
        groupNotice.setCreatedTime(new Date());

        if (noticeMapper.updateByPrimaryKey(groupNotice) != 1){
            return -1;
        }
        return 1;
    }
}
